﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace TinyEngineEditor.Controls
{
    public partial class LogOutput : UserControl
    {
        public LogOutput()
        {
            InitializeComponent();

            Trace.Listeners.Add(new Controls.EditorLogListener(this.txtLog));
        }
    }

    public class EditorLogListener : TraceListener
    {
        private TextBox textBox;
        public EditorLogListener(TextBox textbox)
        {
            this.textBox = textbox;
        }

        public override void Write(string message)
        {
            WriteLine(message);
        }

        public override void WriteLine(string message)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(
            delegate
            {
                textBox.Text += PrefixTimestamp(message.ToString()) + Environment.NewLine;
            }));
            
        }

        private string PrefixTimestamp(string message)
        {
            return string.Format("{0} - {1}", GetTimestamp(), message);
        }

        private string GetTimestamp()
        {
            var dt = DateTime.Now;
            return string.Format("{0}:{1}:{2}:{3}", dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
        }
    }
}
